//
//  GHTabbarViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/14.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "TMTabbarViewController.h"
#import "BBNewHomeViewController.h"
#import "BBHomeViewController.h"
#import "BBHomeMenuPresentViewController.h"
#import "BBSharePresentViewController.h"
#import "BBMineViewController.h"
#import "BBLoginHomeViewController.h"
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "BBSystemSettingViewController.h"
#import "BBHistoryViewController.h"
#import "BBPhoneLoginViewController.h"
@interface TMTabbarViewController ()<TencentSessionDelegate,WXApiDelegate>
@property(nonatomic, strong) UIView                     *bootomView;
@property(nonatomic, strong) TencentOAuth                     *tencentOAuth ;
@end

@implementation TMTabbarViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tabBar.backgroundColor = TM_ThemeBackGroundColor;
        self.tabBar.barTintColor = TM_ThemeBackGroundColor;
        [self.tabBar setBackgroundImage:nil];
        [self.tabBar setShadowImage:[UIImage new]];
        [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:11.f], NSForegroundColorAttributeName : TM_secendTextColor} forState:UIControlStateNormal];
        [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName:TM_ThemeBackGroundColor} forState:UIControlStateSelected];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:TencentQQAppid andDelegate:self];
    [self configBootomView];
    [self confiChildVC];
    // Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

}
- (void)configBootomView{
    self.bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 49)];
    self.bootomView.backgroundColor = [BBThemeColorManger manger].backGroundColor;
    [self.bootomView st_showTopLine];
    self.bootomView.top = [TMUtils tabBarTop];
    [self.view addSubview:self.bootomView];
    __weak typeof(self) weakSelf =  self;
    CGFloat buttonWith  = UIScreenWidth / 4;
    STButton * leftButton = [self deflutButtonWithImageName:@"下一页地"];
    [leftButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedLeftButton];
    }];
    [leftButton setImage:[UIImage imageNamed:@"zuo"] forState:UIControlStateSelected];
    leftButton.left = 0;
    self.leftButton = leftButton;
    
    STButton * rightButton = [self deflutButtonWithImageName:@"下一页地(1)"];
    [rightButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedRightButton];
    }];
    rightButton.left = 1 * buttonWith;
     [rightButton setImage:[UIImage imageNamed:@"you"] forState:UIControlStateSelected];
    STButton * menuButton = [self deflutButtonWithImageName:@"更多"];
    [menuButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedMenuButton];
    }];
    menuButton.left = 2 * buttonWith;
     rightButton.selected = YES;
    self.rightButton = rightButton;
    
//    STButton * numButton = [self deflutButtonWithImageName:@"1"];
//    [numButton setClicAction:^(UIButton *sender) {
//        [weakSelf onSelctedNumberButton];
//    }];
//    numButton.left = 3 * buttonWith;
    
    
    STButton * homeButton = [self deflutButtonWithImageName:@"菜单_首页"];
    [homeButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedHomeButton];
    }];
    homeButton.left = 3 * buttonWith;
}
- (STButton*)deflutButtonWithImageName:(NSString*)imageName{
    CGFloat buttonWith  = UIScreenWidth / 5;
    STButton * leftButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 49)
                                                      title:nil
                                                 titleColor:nil
                                                  titleFont:0
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:imageName]];
    [self.bootomView addSubview:leftButton];
    leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    return leftButton;
}
- (void)confiChildVC{
    

    [self setTabbarChildController:[BBNewHomeViewController new]
                         itemTitle:@""
                         itemImage:nil
                       selectImage:nil
                           itemTag:10000];
    
}

- (void)setTabbarChildController:(UIViewController *)controller itemTitle:(NSString *)title itemImage:(UIImage *)image selectImage:(UIImage *)simage itemTag:(NSInteger)tag {
    
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    simage = [simage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    STNavigationController *navi = [[STNavigationController alloc] initWithRootViewController:controller];
    navi.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:image selectedImage:simage];
    navi.tabBarItem.tag = tag;
    [self addChildViewController:navi];
}

#pragma mark --Action Method
- (void)onSelctedLeftButton{
    UIViewController * vc = self.childViewControllers.firstObject.childViewControllers.lastObject;
    if ([vc isKindOfClass:[STWebViewController class]]) {
        STWebViewController * web = (id)vc;;
        if (web.webView.canGoBack) {
            [web.webView goBack];
        }else{
            [web.navigationController popViewControllerAnimated:YES];
        }
    }else if ([vc isKindOfClass:[BBWebViewController class]]){
        
        BBWebViewController * web = (id)vc;;
        if (web.webView.canGoBack) {
            [web.webView goBack];
        }else{
            [web.navigationController popViewControllerAnimated:YES];
        }
        
    }else{
         [vc.navigationController popViewControllerAnimated:YES];
    }
}
- (void)onSelctedRightButton{
   UIViewController * vc = self.childViewControllers.firstObject.childViewControllers.lastObject;
    if ([[BBNavHistoryManger manger].historyArray containsObject:vc]) {
        if ([BBNavHistoryManger manger].historyArray.lastObject == vc) {
            return;
        }
        NSInteger index = [[BBNavHistoryManger manger].historyArray indexOfObject:vc];
        UIViewController * nextVC = [BBNavHistoryManger manger].historyArray.lastObject;
        if ([nextVC isKindOfClass:[STWebViewController class]]) {
            STWebViewController * webVC = (id)nextVC;
            webVC.shouldNotRecord = YES;
        }
        [vc.navigationController pushViewController:nextVC animated:YES];
    }
}
- (void)onSelctedMenuButton{
    BBHomeMenuPresentViewController * vc = [BBHomeMenuPresentViewController new];
    [vc setOnSelctedMenuButton:^(NSString *title) {
        [self onSelctedPresentMenuWithTitle:title];
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelctedNumberButton{
    
}
- (void)onSelctedHomeButton{
     UIViewController * vc = self.childViewControllers.firstObject.childViewControllers.lastObject;
    [vc.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark --pubilic
- (void)shareWithChosedTitle:(NSString*)title image:(UIImage*)shareImage{
    
    BOOL isAleart = [[NSUserDefaults standardUserDefaults] valueForKey:isAleartKey];
    if (!isAleart) {
        [self showAlertTitle:@"分享后需要返回区块链才能获取奖励哦" message:@"" leftTitle:@"取消" rightTitle:@"确认" block:^(NSString *name) {
            if ([name isEqualToString:@"确认"]) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isAleartKey];
                [self shareWithTitle:title image:shareImage];
            }else{
                
            }
        }];
    }else{
        [self shareWithTitle:title image:shareImage];
    }

}
- (void)shareWithTitle:(NSString*)title image:(UIImage*)shareImage{
    
    BBUserModel * user = [[STUserManger defult] loginedUser];
    NSString *url = user.share;
    if (!user) {
        url = @"http://www.zipengdp.cn/share";
    }
    if ([title isEqualToString:@"QQ"] || [title isEqualToString:@"QQ空间"]) {
        NSData * data = UIImagePNGRepresentation(shareImage);
        
        QQApiURLObject * obj = [QQApiURLObject objectWithURL:[NSURL URLWithString:url]
                                                       title:@"区块浏览器"
                                                 description:@"扫描二维码获取奖励"
                                            previewImageData:data targetContentType:QQApiURLTargetTypeNews];
        UIImage * image = [UIImage imageNamed:@"挖矿"];
        NSData *  imageTrubData =  UIImageJPEGRepresentation(image, 0.0001);
        QQApiImageObject * imageObj = [QQApiImageObject objectWithData:data previewImageData:imageTrubData title:@"扫描二维码获取奖励" description:@"扫描二维码获取奖励"];
        SendMessageToQQReq *req = [SendMessageToQQReq
                                   reqWithContent:imageObj];
        //向QQ发送消息，查看是否可以发送
        if ([title isEqualToString:@"QQ空间"]) {
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        }else{
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        }
        
        
    }else{
        
        
        NSData *imageData = UIImageJPEGRepresentation(shareImage, 1);
//        UIImage * shareTrumImage = [uii]
        NSData *imageTrubData =  UIImageJPEGRepresentation(shareImage, 0.0001);
        CGFloat m = imageTrubData.length/1024.0;
        
        if (m > 30) {
            UIImage * image = [UIImage imageNamed:@"挖矿"];
            imageTrubData =  UIImageJPEGRepresentation(image, 0.0001);
        }
        CGFloat birgM = imageData.length/1024.0/1024.0;
        
        //        WXImageObject *ext = [WXImageObject object];
        //        // 小于10MB
        //        ext.imageData = imageData;
        
        
        WXImageObject *imageObj = [WXImageObject object];
        imageObj.imageData = imageData;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.mediaObject = imageObj;
        [message setThumbData:imageTrubData];
        message.messageExt = @"区块浏览器分享";
        
        
        SendMessageToWXReq  *req = [SendMessageToWXReq new];
        req.text = @"区块浏览器";
        req.bText = NO;
        req.scene = WXSceneSession;
        req.message = message;
        if ([title isEqualToString:@"朋友圈"]) {
            req.scene = WXSceneTimeline;
        }
        [WXApi sendReq:req];
    }
}
#pragma mark --BBHomeMenuPresentViewControllerHanle
//@[@"头像",@"收藏网址",@"夜间模式",@"刷新",@"收藏/历史",@"退出"，@"设置"，@"分享"]
- (void)onSelctedPresentMenuWithTitle:(NSString*)title{
    NSLog(@"%@",title);
     BBUserModel * user =   [STUserManger defult].loginedUser;
    UINavigationController * nav = self.childViewControllers.firstObject;
    if ([title isEqualToString:@"收藏网址"]) {
        STWebViewController * webVC = nav.childViewControllers.lastObject;
        if ([webVC isKindOfClass:[STWebViewController class]]) {
            BBScanHistoryModel * model = [BBScanHistoryModel new];
            model.url = webVC.urlStr;
            model.title = webVC.forceTitle;
            [[BBHistoryManger manger] addColletionModel:model];
            [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
        }
    }
    if ([title isEqualToString:@"退出"]) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [UIView animateWithDuration:0.4 animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
            window.centerX = UIScreenWidth / 2;
            window.centerY = UIScreenHeight / 2;
        } completion:^(BOOL finished) {
            exit(0);
        }];
    }
    if ([title isEqualToString:@"分享"]) {
//        if (user.userID.description) {
            BBSharePresentViewController * vc = [BBSharePresentViewController new];
            [vc setShareButtonHandle:^(NSString *title, UIImage *shareImage) {
                
                [self shareWithChosedTitle:title image:shareImage];
            }];
            [self presentViewController:vc animated:NO completion:nil];
//        }else{
//            BBLoginHomeViewController * vc = [BBLoginHomeViewController new];
//            [nav pushViewController:vc animated:YES];
//            
//        }

    }
    if ([title isEqualToString:@"头像"]) {
       
        if (user.userID.description) {
             [self gotoMineViewController];
        }else{
            BBPhoneLoginViewController * vc = [BBPhoneLoginViewController new];
            [nav pushViewController:vc animated:YES];
            
        }
       
    }
    if ([title isEqualToString:@"夜间模式"]) {
        [[BBThemeColorManger manger] changeColorStyle:BBThemeColorStyleBlacklook];
        TMTabbarViewController * vc =  [TMTabbarViewController new];
        UIWindow * window =     [UIApplication sharedApplication].delegate.window;
        window.rootViewController = vc;
        [window st_showAnimationWithType:STAnimationTypesuckEffect];
        
    }
    if ([title isEqualToString:@"日间模式"]) {
        
        [[BBThemeColorManger manger] changeColorStyle:BBThemeColorStyleNormal];
        TMTabbarViewController * vc =  [TMTabbarViewController new];
        UIWindow * window =     [UIApplication sharedApplication].delegate.window;
        window.rootViewController = vc;
        [window st_showAnimationWithType:STAnimationTypesuckEffect];
    }
    if ([title isEqualToString:@"设置"]) {
        BBSystemSettingViewController * vc = [BBSystemSettingViewController new];
        [nav pushViewController:vc animated:YES];
        
    }
    if ([title isEqualToString:@"收藏/历史"]) {
        BBHistoryViewController * vc = [BBHistoryViewController new];
        [nav pushViewController:vc animated:YES];
        
    }
    if ([title isEqualToString:@"刷新"]) {
        BBNewHomeViewController * homeVC = (id)self.childViewControllers.firstObject.childViewControllers.firstObject;
        [homeVC.tableView.mj_header beginRefreshing];
        
    }
    
}

- (void)gotoMineViewController{
    NSArray * array =self.childViewControllers.firstObject.childViewControllers;
    BBMineViewController * mine;
    for (UIViewController * vc in array) {
        if ([vc isKindOfClass:[BBMineViewController class]]) {
            mine = vc;
        }
    }
    UINavigationController * nav = self.childViewControllers.firstObject;
    if (mine) {
      [nav popToViewController:mine animated:YES];
    }else{
         BBMineViewController * vc = [BBMineViewController new];
         [nav pushViewController:vc animated:YES];
    }
   
    
}

#pragma mark --TencentSessionDelegate
/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req{
    
}

/**
 处理来至QQ的响应
 */
- (void)onResp:(QQBaseResp *)resp{
    if (!resp.errorDescription.length) {
         [TMUtils sendGetShareAwardRequest];
      //  [SVProgressHUD showSuccessWithStatus:@"qq分享成功"];
    }else{
         [SVProgressHUD showSuccessWithStatus:@"您取消了qq分享"];
    }
}

/**
 处理QQ在线状态的回调
 */
- (void)isOnlineResponse:(NSDictionary *)response;{
    
}
@end

